import axios from 'axios';

class Http {
    constructor() {
        // 基础路径
        this.baseURL = "http://localhost:3002";
        // 超时时间
        this.timeout = 5000
    }
    mergeOptions(options) {
        return {
            baseURL: this.baseURL,
            timeout: this.timeout,
            withCredentials: true, // 允许携带cookie
            ...options
        }
    }
    createInterceptor(instance) {
        instance.interceptors.request.use(options => {
            //添加请求头
            if (localStorage.getItem('Authorization')) {
                options.headers.token = localStorage.getItem('Authorization');
            }
            return options;
        }, err => {
            return Promise.reject(err);
        });
        instance.interceptors.response.use(response => {
            return Promise.resolve(response.data)
        }, err => {
            Promise.reject(err);
        });
    }
    request(options) {
        // 创建单独的axios实例，好处是单独为每个请求创建拦截器
        const instance = axios.create();
        // 设置拦截器
        this.createInterceptor(instance);
        // 合并请求对象
        options = this.mergeOptions(options);
        return instance(options);
    }
    get(url, options = {}) {
        return this.request({
            url,
            method: 'get',
            ...options
        })
    }
    post(url, options={}) {
        return this.request({
            url,
            method: 'post',
            ...options
        })
    }
    put(url, options) {
        return this.request({
            url,
            method: 'put',
            ...options
        })
    }
}
const http = new Http();
export default http;

